<style scoped>
.wraper {
    padding: 0;
    margin-top: -20px;
}

.search {
    padding-bottom: 20px;
}

.search span {
    color: #68777c;
    font-weight: bold;
    padding-right: 18px;
}

.search button {
    background-color: #00a8f7;
    color: #fff;
    margin-left: 8px;
}

.top {
    margin-bottom: 20px;
    border-top: 1px dashed #cccccc;
}

.detail {
    border-top: 1px dashed #cccccc;
}

.wraper .headline {
    position: relative;
    font-size: 12px;
    color: #303134;
    font-weight: bold;
    margin: 10px 0;
    line-height: 32px;
    height: 32px;
}

.wraper .add-agent {
    position: absolute;
    top: 0px;
    right: 30px;
    background-color: #348bf2;
    color: #fff;
}

.iconfont {
    font-size: 14px;
}



/* 分页 start */

.pagestyle {
    margin: 20px 0;
    float:right;
    padding-right: 15px;
}


/* 分页 end */

.leftside{
    overflow-y: auto;
   
}
.leftside-search{
    padding: 10px;
}
.rightside{
    border-left: 1px solid #e9eaec;
}
.leftside-list{
    overflow-y: auto;
}
.leftside-list ul li{
    padding: 10px;
    cursor: pointer;
}

.leftside-list ul li:hover{ 
    background: rgba(64,116,225,0.3);
    color:#4074e1;
    border-right: 4px solid #4074e1;
}
.leftside-list ul li:hover a{
    color:#4074e1;
}
.leftside-list .active,.leftside-list ul li.active:hover{
    background-color: #4074e1;
    color:#fff;
}
.leftside-list .active a,.leftside-list ul li.active:hover a{
    color: #fff;
}
.leftside-listspan{
    max-width: 75%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    display: inline-block;
    vertical-align: bottom;
    color: #000;
}
.leftside-edit{
    font-size: 18px;
}
.poptip-ul{
    color: #000;
}
.leftside-list ul li .poptip-ul li:hover{
    background-color: #4074e1;
    color:#fff;
}
.rightside-title{
    padding: 20px;
}
.rightside-title h3{
    display: inline-block;
    font-size: 18px;
    font-weight: normal;
}
.title-total{
    font-size: 14px;
    color: #999;
}
.fr{
    float: right;
}
.rightside-content{
    padding: 5px;
}
</style>


<template>
    <div class="member-manage">
        <product-title></product-title>
        <div class="wraper">
            <Row>
                <Col :xs="8" :sm="8" :md="8" :lg="4">
                    <div class="leftside">
                        <div class="leftside-search">
                            <Input placeholder="输入机构名称" v-model="orgName">
                                <Button slot="append" icon="ios-search" @click="getorg()"></Button>
                            </Input>
                        </div>
                        <div class="leftside-list" :style="leftHeight">
                            <ul>
                                <li v-for="(item,index) in orglist" :key="item.id" :class="active == index ?'active':''" @click="leftActive(index)"><Icon type="document-text"></Icon>
                                    <a class="leftside-listspan" href="javascript:;" :title="item.name">{{item.name}}</a>
                                    <Poptip trigger="hover" placement="bottom" style="margin-left: 15px" width="100%">
                                        <Icon @click.stop="drop" class="leftside-edit" type="ios-plus-outline"></Icon>
                                        <div class="api" slot="content">
                                            <ul class="poptip-ul">
                                                <li @click.stop="editorg(index)">编辑账号</li>
                                                <li @click.stop="reductionpwd(index)">还原密码</li>
                                            </ul>
                                        </div>
                                    </Poptip>
                                </li>                                                 
                            </ul>
                        </div>
                    </div>
                </Col>
                <Col :xs="14" :sm="14" :md="14" :lg="20">
                    <div class="rightside" :style="rightHeight">
                        <div class="rightside-title">
                            <h3>{{rightTitle}}</h3>
                            <span class="title-total">（{{emplyeeTotal}}人）</span>
                            <Button type="primary" shape="circle" icon="plus" class="fr" @click="addmember()">添加成员</Button>
                        </div>
                        <div class="rightside-content">
                            <Table border ref="selection" :columns="columns4" :data="data1"></Table>
                             <Page class-name="pagestyle" :total="emplyeeTotal" show-total @on-change="pageChange"></Page>
                        </div>
                    </div>
                </Col>
            </Row>
        </div>
        <Modal v-model="showAddModal" width="450" :mask-closable=false title="添加成员" @on-ok="add" :loading="loading">
            <Row>
                <Col span="24">
                    <Transfer
                        :data="data2"
                        :target-keys="targetKeys2"
                        filterable
                        :list-style="listStyle"
                        :filter-method="filterMethod"
                        @on-change="handleChange2"
                        :titles="titles"
                        >
                    </Transfer>
                </Col>
            </Row>
        </Modal>
        <Modal v-model="showeditModal" :mask-closable='closeable' width="600" title="编辑账号信息" @on-ok="addorg()" :loading="loading">
            <Row>
                <Col span="18" offset="1">
                    <Form :model="org" ref="org" :rules="ruleValidate" :label-width="120">
                        <Form-item label="账号名：" prop="name" required>
                            <Input v-model="org.name" placeholder="请输入账号登录名"></Input>
                        </Form-item>
                        <Form-item label="登录名：" prop="login_name" required>
                            <Input v-model="org.login_name" placeholder="请输入账号登录名"></Input>
                        </Form-item>
                        <Form-item label="登录密码：" prop="pwd" required>
                            <Input v-model="org.pwd" type="password" placeholder="请输入登录密码"></Input>
                        </Form-item>
                        <Form-item label="确认密码：" prop="pwd_two" required>
                            <Input v-model="org.pwd_two" type="password" placeholder="请再次输入登录密码"></Input>
                        </Form-item>
                        <Form-item label="角色：" prop="role_id" required>
                            <Select v-model="org.role_id" style="width:306px" placeholder='请选择角色'>
                                <Option :value="item.id" v-for="item in roleList" :key="item.id" >{{item.name}}</Option>
                            </Select>
                        </Form-item>
                    </Form>
                </Col>
            </Row>
        </Modal>
    </div>
</template>

<script>
import productTitle from '../../components/productTitle'
import { getAllOrgList ,getUndistributed , getOrgEmployee ,addOrgEmployee , delOrgEmployee , getPermission , setPermission , resetPwd } from '../../api/org'
import { getRoleList} from '../../api/role'
export default {
    data() {
        const validatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入密码'));
            } else {
                if (this.org.pwd_two !== '') {
                    // 对第二个密码框单独验证
                    this.$refs.org.validateField('pwd_two');
                }
                callback();
            }
        };
        const validatePassCheck = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            } else if (value !== this.org.pwd) {
                callback(new Error('两次输入的密码不匹配!'));
            } else {
                callback();
            }
        };
        return {
            listStyle: {                
                height: '300px'
            },
            orgName:'',
            active:0,
            showAddModal:false,
            showeditModal:false,
            closeable: false,
            loading:true,
            leftHeight: {
                height: '0px'
            },
            rightHeight: {
                height: '0px'
            },
            dataLeft: [
                
            ],
            org:{
                name:'',
                login_name:'',
                pwd:'',
                role_id:''
            },
            rightTitle:'',
            page:1,
            emplyeeTotal:0,
            orglist:[],
            roleList:[],
            titles:['未分配成员','已选择成员'],
            undistributed:[],
            emplyee:[],
            columns4: [
                    {
                        title: '工号',
                        key: 'job_num',
                        align: 'center',
                    },
                    {
                        title: '姓名',
                        key: 'name',
                        align: 'center',
                    },
                    {
                        title: '电话',
                        key: 'mobile',
                        align: 'center',
                    },
                    {
                        title: '操作',
                        key: 'action',
                        width: 150,
                        align: 'center',
                        render: (h, params) => {
                            return h('div', [                                
                                h('Button', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    on: {
                                        click: () => {
                                            this.remove(params.row.id)
                                        }
                                    }
                                }, '删除')
                            ]);
                        }
                    }
                    
                ],
                data1: [
                    
                ],
                data2: [
                    
                ],
                targetKeys2: [
                    
                ],
                ruleValidate: {
                    name:[
                        { required: true, message: '帐号名不能为空', trigger: 'blur' }
                    ],
                    pwd: [
                        { validator: validatePass, trigger: 'blur' }
                    ],
                    pwd_two: [
                        { validator: validatePassCheck, trigger: 'blur' }
                    ],
                    login_name: [
                        { required: true, message: '登录名不能为空', trigger: 'blur' },
                    ],
                    role_id: [
                        { required: true, message: '请选择角色', trigger: 'change' }
                    ],
                },
                
        }
    },
    components: {
        productTitle
    },
    created() {
        let winHeight = screen.availHeight;
        this.leftHeight.height = (winHeight  - 280 - 32) + 'px';
        this.rightHeight.height = (winHeight - 280) + 'px';
        this.getRole()
        this.getorg()
        this.getUndistributed()
        
    },
    methods: {

        editorg(index){
            this.showeditModal = true
            this.org.oid = this.orglist[index].oid
            var _param = {
                oid:this.orglist[index].oid
            }
            new Promise((resolve, reject) => {
                getPermission(_param).then(response => {
                    if (response.data.err == 0) {
                        this.org =  response.data.data
                        this.org.pwd_two = response.data.data.pwd
                        this.org.oid =  this.orglist[index].oid                      
                    } else {
                        this.$refs['org'].resetFields();
                        //this.$Message.error(response.data.info);
                        
                    }
                    resolve();
                }).catch(error => {
                    reject(error);
                });
            });
        },
        addorg(){
            this.$refs['org'].validate((valid) => {
                if (valid) {                    
                    new Promise((resolve, reject) => {
                        setPermission(this.org).then(response => {
                            if (response.data.err == 0) {
                                this.showeditModal = false;
                                this.loading = true;
                                this.getorg()
                                this.$Message.success(response.data.info)
                            } else {
                                this.$Message.error(response.data.info)
                                setTimeout(() => {
                                    this.loading = false;
                                    this.$nextTick(() => {
                                        this.loading = true;
                                    });
                                }, 2000);
                            }
                            resolve();
                        }).catch(error => {
                            reject(error);
                        });
                    });                                    
                } else {
                    // 通过loading来阻止modal隐藏，然后手动修改loading来充值确定按钮
                    setTimeout(() => {
                        this.loading = false;
                        this.$nextTick(() => {
                            this.loading = true;
                        });
                    }, 2000);
                }    
            })
        },
        reductionpwd(index){
            this.$Modal.confirm({
                title: '提示',
                content: '是否要还原登录密码?',
                onOk: () => {
                    let _params = {
                        oid:this.orglist[index].oid
                    }
                    new Promise((resolve, reject) => {
                        resetPwd(_params).then(response => {
                            if (response.data.err == 0) {
                                this.$Message.success(response.data.info);
                            } else {
                                this.$Message.error(response.data.info);
                            }
                            resolve();
                        }).catch(error => {
                            reject(error);
                        });
                    });
                }
            })
        },
        // 页码改变
        pageChange(page) {
            this.page = page
            this.getOrgEmployee()
        },
        addmember(){
            this.getUndistributed()
            this.showAddModal = true
        },
        getMockData(){
            this.targetKeys2 = []
            let mockData = []
            let _undistributed =  this.undistributed
            let _length = _undistributed.length
            this.data2 =[]
            for (let i = 0; i < _length; i++) {
                let _boj = {}
                this.data2.push({
                    key:_undistributed[i].id.toString(),
                    label:_undistributed[i].name
                });
            }
            
        },
        // getTargetKeys(){
        //     return this.getMockData()
        //                 .filter(() => Math.random() * 2 > 1)
        //                 .map(item => item.key);
        // },
        handleChange2 (newTargetKeys) {
            this.targetKeys2 = newTargetKeys;
        },
        filterMethod (data, query) {
            return data.label.indexOf(query) > -1;
        },
        add(){

        },
        //获取角色列表
        getRole() {
            let _params = {
                cate:2
            }
            new Promise((resolve, reject) => {
                getRoleList(_params).then(response => {
                    if (response.data.err == 0) {
                        this.roleList = response.data.data;
                    } else {
                        this.$Message.error(response.data.info);
                    }
                    resolve();
                }).catch(error => {
                    reject(error);
                });
            });
        },
        getorg(){
            var _param = {
                name:this.orgName
            }
            new Promise((resolve,reject)=>{
                getAllOrgList(_param).then(response=>{
                    if (response.data.err == 0) {
                        this.orglist =  response.data.data    
                        this.yid = this.orglist[0].id
                        this.rightTitle = this.orglist[0].name             
                    } else {
                                             
                    }
                    resolve(this.getOrgEmployee());
                }).catch(error => {
                    reject(error);
                });
            })
        },
        getUndistributed(){
            new Promise((resolve,reject)=>{
                getUndistributed().then(response=>{
                    if (response.data.err == 0) {

                        this.undistributed =  response.data.data                   
                    } else {
                                             
                    }
                    resolve(this.getMockData());
                }).catch(error => {
                    reject(error);
                });
            })
        },
        getOrgEmployee(){
            let _param = {
                yid:this.yid,
                p:this.page
            }
            new Promise((resolve,reject)=>{
                getOrgEmployee(_param).then(response=>{
                    if (response.data.err == 0) {
                        this.data1 =  response.data.data.list   
                        this.emplyeeTotal =  response.data.data.total           
                    } else {
                                             
                    }
                    resolve();
                }).catch(error => {
                    reject(error);
                });
            })
        },
        add(){
            if(this.targetKeys2.length > 0){
                let _param={
                    yid:this.yid,
                    uids:this.targetKeys2   
                }
                new Promise((resolve,reject)=>{
                    addOrgEmployee(_param).then(response=>{
                        console.log(response.data)
                        if (response.data.err == 0) {
                            this.showAddModal = false;
                            this.loading = true;
                            this.getOrgEmployee()              
                        } else {
                            this.$Message.error(response.data.info);
                            setTimeout(() => {
                                this.loading = false;
                                this.$nextTick(() => {
                                    this.loading = true;
                                });
                            }, 2000);                  
                        }
                        resolve();
                    }).catch(error => {
                        reject(error);
                    });
                })
            }else{
                this.$Message.error('请选择至少一名成员！')
                setTimeout(() => {
                    this.loading = false;
                    this.$nextTick(() => {
                        this.loading = true;
                    });
                }, 2000);
            }
            
        },
        remove(id){
            this.$Modal.confirm({
                title: '提示',
                content: '是否要删除该条记录?',
                onOk: () => {
                    var _param = {
                        yid:this.yid,
                        uid:id
                    }
                    new Promise((resolve,reject)=>{
                        delOrgEmployee(_param).then(response=>{
                            console.log(response.data)
                            if (response.data.err == 0) {
                                this.getOrgEmployee()                 
                            } else {
                                                    
                            }
                            resolve();
                        }).catch(error => {
                            reject(error);
                        });
                    })
                },
            });                     
        },
        leftActive(index){
            this.active = index
            this.rightTitle = this.orglist[index].name
            this.yid = this.orglist[index].id
            this.page = 1
            this.getOrgEmployee()
        }
    }
}
</script>
